/*
 * Socket.cpp
 *
 *  Created on: 15/05/2011
 *      Author: dela
 */

#include <stdlib.h>
#include <string.h>
#include <winsock2.h>
#include <iostream>
#include "Socket.h"

/**
 *
 */
Socket::Socket(int port) {
	struct sockaddr_in serv_addr;

	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		exit(1);
	}

	memset((char *) &serv_addr, 0, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(port);
	serv_addr.sin_addr.s_addr = INADDR_ANY;

	if (bind(sockfd, (struct sockaddr *) &serv_addr,
			(socklen_t) sizeof(struct sockaddr)) < 0) {
		exit(1);
	}

	listen(sockfd, 10);
}


/**
 *
 */
Socket::~Socket() {
	std::cout<<"closesocket"<<std::endl;
	//closesocket(sockfd);
}


/**
 *
 */
void Socket::shutdownSocket() {
	shutdown(sockfd, SD_BOTH);
	closesocket(sockfd);
}


/**
 *
 */
unsigned int Socket::acceptConnection() {
	struct sockaddr_in cli_addr;
	int clilen = (socklen_t) sizeof(cli_addr);
	return accept(sockfd, (struct sockaddr*) &cli_addr, &clilen);
}

/**
 *
 */
int Socket::connectSocket(char *ip, int port) {
	std::cout<<"connectSocket"<<std::endl;
	struct hostent *he;
	struct sockaddr_in their_addr;
	he = gethostbyname(ip);
	std::cout<<"prepre sockfd" << sockfd<<std::endl;
	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	their_addr.sin_family = AF_INET;
	their_addr.sin_port = htons(port);
	their_addr.sin_addr = *((struct in_addr *) he->h_addr);
	memset(&(their_addr.sin_zero), 8, sizeof(int));

	return connect(sockfd, (struct sockaddr *) &their_addr, sizeof(struct sockaddr));
}



